package com.byq.mcpanus.controller;

import com.byq.mcpanus.service.ChatService;
import com.byq.mcpanus.model.MyConversation;
import com.byq.mcpanus.repository.MyConversationRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import org.springframework.security.access.prepost.PreAuthorize;

import java.util.List;

@RestController
public class ChatController {
    @Autowired 
    private ChatService chatService;
    @Autowired
    private MyConversationRepository myConversationRepository;

    @PreAuthorize("hasRole('CUSTOMER')")
    @PostMapping("/ask")
    public ResponseEntity<String> ask(@RequestBody java.util.Map<String, Object> body) {
        try {
            String question = (String) body.get("question");
            String domain = (String) body.get("domain");
            String cid = body.get("cid") != null ? (String) body.get("cid") : null;
            String imageBase64 = body.get("imageBase64") != null ? (String) body.get("imageBase64") : null;
            String answer = chatService.ask(question, cid, domain, imageBase64);
            return ResponseEntity.ok(answer);
        } catch (Exception e) {
            return ResponseEntity.badRequest().body("Error: " + e.getMessage());
        }
    }

    @PreAuthorize("hasRole('CUSTOMER')")
    @GetMapping("/conversations")
    public ResponseEntity<List<MyConversation>> getAllConversations() {
        List<MyConversation> list = myConversationRepository.findAll();
        return ResponseEntity.ok(list);
    }
}
